﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sexybeauty.Web.WebLogic;
using Sexybeauty.Core.Biz;
using System.Drawing;
using Sexybeauty.Framework.Common;
using Sexybeauty.Web.WebLogic.Models;

namespace Sexybeauty.Web.Controllers
{
    //[ErrorHandle]
    public class AccountController : Controller
    {
        #region 登陆
        [HttpPost]
        public ActionResult quicklogin(string username,string password)
        {
            if (UserBiz.Login(username, password, false) == null) //快捷登陆失败
            {
                Session["quickloginname"] = username;
                return Redirect("/account/login");
            }
            return Redirect("/");
        }
        [HttpGet]
        public ActionResult login()
        {
            ViewBag.Username = Session["quickloginname"];
            return View();
        }
        [HttpPost]
        public ActionResult login(string username, string password, string validator)
        {
            ViewBag.Username = username;
            if (String.IsNullOrEmpty(username) ||
              String.IsNullOrEmpty(password) ||
              String.IsNullOrEmpty(validator))
            {
                ViewBag.Error = "缺少必填项！";
                return View();
            }
            if (ValidateValidateCode(validator))
            {
                var user = UserBiz.Login(username, password, false);
                if (user == null)
                {
                    ViewBag.Error = "登陆失败，用户名或密码错误！";
                    return View();
                }
                else
                {
                    if (!user.IsActivate)
                    {
                        return Redirect("/account/beactivate?n="+Sexybeauty.Framework.Common.AesAlgorithm.Encrypt(username));
                    }
                    return Redirect("/");
                }
            }
            ViewBag.Error = "验证码输入错误！";
            return View();
        }
        /// <summary>
        /// 验证验证码是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValidateValidateCode(string code)
        {
            bool result;

            string token = Request.Params["token"];
            if (token == null)
            {
                result = false;
            }
            else
            {
                token = Cryptogram.CommonEncrypt(token);
                //过虑加密后出现的非法字符
                token = token.Replace("/", "");
                token = token.Replace("+", "");
                token = token.Replace("=", "");
                token = token.Substring(0, 4).ToString();
                token = token.ToLower();
                //过虑0为O,I和1
                token = token.Replace("0", "o");
                token = token.Replace("1", "i");
                string validStr = code.ToLower();
                //o,0转换，i,1转换
                validStr = validStr.Replace("0", "o");
                validStr = validStr.Replace("1", "i");
                if (validStr != token)
                    result = false;
                else
                    result = true;
            }
            return result;
        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="t"></param>
        [HttpGet]
        public void ValidateToken(string t)
        {
            const int width = 60, height = 25;

            Bitmap aBmp = new Bitmap(width, height);
            Graphics aGrph = Graphics.FromImage(aBmp);
            aGrph.FillRectangle(new SolidBrush(Color.FromArgb(68, 68, 68)), 0, 0, width, height);//255,153,0

            //string adPitch = ssolib.Cryptogram.CommonDecrypt(Request.QueryString["yymm"].ToString());

            //为了解决浏览器后退，验证码不刷新的问题，对验证码的实现做了修改。 By Zhenli W.  2004-03-21
            string adPitch = Cryptogram.CommonEncrypt(t);

            adPitch = adPitch.Replace("/", "");
            adPitch = adPitch.Replace("+", "");
            adPitch = adPitch.Replace("=", "");

            adPitch = adPitch.Substring(0, 4);
            /*if(adPitch.Length < 4)
            {
                for(int i=0;i<4-adPitch.Length;i++)
                {
                    adPitch = adPitch + (new Random(i)).Next(0,9).ToString();
                }
            }*/
            //End Updated by Zhenli W.

            adPitch = adPitch.ToUpper();

            //过虑0为O,I和1
            adPitch = adPitch.Replace("0", "O");
            adPitch = adPitch.Replace("1", "I");
            new VerifyCodeImage().CreateImageOnPage(adPitch, 3, System.Web.HttpContext.Current);

        }
        public void logout() 
        {
            System.Web.Security.FormsAuthentication.SignOut();
        }
        #endregion
        
        #region 注册
        [HttpGet]
        public ActionResult register() 
        {
            return View();
        }
        [HttpPost]
        public ActionResult register(RegisterModel model)
        {
            if (UserBiz.Register(new Core.Inf.LogicEntity.MemberEntity()
            {
                Area = (Core.Inf.LogicEntity.AreaCode)model.area,
                Birthday = model.birthday.ToDateTime(DateTime.Parse("1990-01-01")),
                Email = model.username,
                Gender = model.sex == 0 ? Core.Inf.LogicEntity.Gender.Male : Core.Inf.LogicEntity.Gender.Female,
                IsActivate = false,
                IsRefuse = false,
                Location = model.local,
                NickName = model.nickname,
                Password = model.password,
                Phone = string.Empty,
                QQ = string.Empty,
                RcdDate = DateTime.Now,
                Role = (Core.Inf.LogicEntity.SocialRole)model.role,
                UserName = model.username
            }) != null)
            {
                return Redirect("/account/registercomplete");
            }
            return Redirect("/account/register");
        }
        public ActionResult registercomplete()
        {
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="username"></param>
        /// <returns>0:可以注册，1：已经存在</returns>
        public int usernameonly(string username)
        {
            return UserBiz.UserNotExists(username) ? 0 : 1;
        }
        public ActionResult activation()
        {
            if (UserBiz.Activation(HttpContext.GetParameter("token"))!=null)
            {
                ViewBag.Success = true;
                ViewBag.Message = "激活成功！";
            }
            else
            {
                ViewBag.Success = false;
                ViewBag.Message = "激活失败！";
            }
            return View();
        }
        public ActionResult resend() 
        {
            return View();
        }
        [HttpPost]
        public ActionResult resend(string username, string validator)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(validator) || !ValidateValidateCode(validator))
            {
                ViewBag.Error = "输入用户名或验证码有误，请重新输入";
                return View();
            }
            if (UserBiz.ReSendActiveMail(username) == null)
            {
                ViewBag.Error = "非注册用户名，请重新输入";
                return View();
            }
            return Redirect("/account/resendcomplete");
        }
        #endregion

        #region 找回密码
        public ActionResult misspassword() 
        {
            return View();
        }
        [HttpPost]
        public ActionResult misspassword(string username, string validator)
        {
            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(validator) || !ValidateValidateCode(validator))
            {
                ViewBag.Error = "输入用户名或验证码有误，请重新输入";
                return View();
            } 
            if (!UserBiz.ResendPasswordReset(username))
            {
                ViewBag.Error = "非注册用户名，请重新输入";
                return View();
            }
            return Redirect("/account/misspasswordcomplete");
        }
        public ActionResult misspasswordcomplete()
        {
            return View();  
        }
        public ActionResult verifyresetpassword()
        {
            var user = UserBiz.CheckToken(HttpContext.GetParameter("token"));
            if (user == null)
            {
                ViewBag.Success = false;
                ViewBag.Message = "重置密码验证失败，您的请求超时了";
                return View();
            }
            Session["username"] = user.UserName;
            return Redirect("/account/resetpassword");
        }
        public ActionResult resetpassword()
        {
            object username = Session["username"];
            if (username == null)
            {
                return Redirect("/account/login");
            }
            ViewBag.Username = username;
            return View();
        }
        [HttpPost]
        public ActionResult resetpassword(string password)
        {
            object username = Session["username"];
            if (username == null)
            {
                return Redirect("/account/login");
            }
            if (UserBiz.ChangePassword(username.ToString(), password) != null)
            {
                return Redirect("/account/resetsuccess");
            }
            return Redirect("/account/resetfail");
        }
        public ActionResult resetsuccess()
        {
            return View();
        }
        public ActionResult resetfail()
        {
            return View();
        }
        #endregion

        public ActionResult beactivate() 
        {
            return View();
        }

    }
}
